//------------------------------------------------------------------------------
// <copyright file="ObservableCollectionExtension.cs" company="Damian Antonowicz">
//       copyright © 2010 Damian Antonowicz
// </copyright>
// <author>Damian Antonowicz</author>
// <email>poczta@damianantonowicz.pl</email>
//------------------------------------------------------------------------------

using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.ComponentModel;
using System.Linq;

namespace DAnton.Utilities.Extensions
{
    public static class ObservableCollectionExtension
    {
        public static void Sort<T, TResult>(this ObservableCollection<T> collection,
                                            Func<T, TResult> expression, 
                                            ListSortDirection sortDirection)
        {
            switch (sortDirection)
            {
                case ListSortDirection.Ascending:
                    {
                        ClearCollectionAndAddItems(collection, collection.OrderBy(expression).ToList());
                        break;
                    }
                case ListSortDirection.Descending:
                    {
                        ClearCollectionAndAddItems(collection, collection.OrderByDescending(expression).ToList());
                        break;
                    }
            }
        }

        private static void ClearCollectionAndAddItems<T>(ObservableCollection<T> collection, 
                                                          IEnumerable<T> items)
        {
            collection.Clear();
            collection.AddRange(items);
        }

        public static void ForEach<T>(this ObservableCollection<T> collection, Action<T> action)
        {
            if (action == null)
                throw new ArgumentNullException("action");

            foreach (T item in collection)
                action(item);
        }
    }
}
